package com.quasar.hpatient.view.personal.register.registerFragment;

import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.Gson;
import com.quasar.hpatient.MainAppliaction;
import com.quasar.hpatient.R;
import com.quasar.hpatient.base.BaseFragment;
import com.quasar.hpatient.constant.ConstantManger;
import com.quasar.hpatient.model.httpmodel.DataStateResult;
import com.quasar.hpatient.model.litePalmodel.Aerainfodb;
import com.quasar.hpatient.model.medicalmodel.GeographyBean;
import com.quasar.hpatient.model.medicalmodel.PatientInfoData;
import com.quasar.hpatient.onInterface.viewInterface.UiInterface;
import com.quasar.hpatient.presenter.AloneUserPresenter;
import com.quasar.hpatient.utils.GetJsonDataUtil;
import com.quasar.hpatient.utils.LogAndToastUtil;
import com.quasar.hpatient.view.personal.register.RegisterEditActivity;
import com.quasar.hpatient.widget.SelectWidget;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.FragmentArg;
import org.androidannotations.annotations.ViewById;
import org.json.JSONArray;

import java.util.ArrayList;
import java.util.List;

/**
 * author : 许建宏
 * Date: 2017/11/27 0027
 * View:注册地址
 */
@EFragment(R.layout.register_address_fragment_layout)
public class RegisterAddressFragment extends BaseFragment implements UiInterface<DataStateResult> {

    private AloneUserPresenter aloneUserPresenter;
    private List<Aerainfodb> aerainfodbList;

    @ViewById(R.id.ew_address)
    SelectWidget ew_address;

    @FragmentArg
    PatientInfoData patient;

    @AfterViews
    void init(){
        initView();
        initData();
    }

    @Click(R.id.tv_next)
    public void tv_next(){

        String address=ew_address.getText().toString().trim();
        if(address==null || address.length()==0){
            msg("请输入联系地址");
            return;
        }
        aloneUserPresenter.AloneUserData(ConstantManger.USERADDRESS,address,ConstantManger.TABLEUSERINFO);
    }

    @Click(R.id.tv_last)
    public void tv_last(){
        RegisterEditActivity.ViewPage(2);
    }

    @Click(R.id.tv_skip)
    public void tv_skip(){
        RegisterEditActivity.ViewPage(4);
    }

    @Override
    public void initView() {

        if(patient!=null){
            if(patient.getAddress()!=null && patient.getAddress().length()>0){
                ew_address.setText(patient.getAddress());
            }
        }
    }

    @Override
    public void initData() {
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        aerainfodbList= MainAppliaction.getInstance().getAerainfoList();
        aloneUserPresenter=new AloneUserPresenter(this);
    }

    @Override
    public void onViewSuccess(DataStateResult data) {
        if(data.getMsgCode().equals("0x00000000")){
            RegisterEditActivity.ViewPage(4);
        }
    }

    @Override
    public void onViewError(String msg) {

        if(msg!=null){
            msg(msg);
        }
    }

    @Override
    public void onViewRefreshUI() {

    }

    //选择地址
    @Click(R.id.ew_address)
    public void ew_address(){
        ShowPickerView();
    }

    private void ShowPickerView() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerView.Builder(getActivity(), new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1).getPickerViewText() +
                        options2Items.get(options1).get(options2) +
                        options3Items.get(options1).get(options2).get(options3);

                ew_address.setText(tx);
            }
        })
                .setTitleText("地区选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .setOutSideCancelable(false)// default is true
                .build();
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }




    /**
     * 添加地址选择
     */
    private Thread thread;
    private boolean isLoaded = false;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private ArrayList<GeographyBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 写子线程中的操作,解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    LogAndToastUtil.toast(getActivity(), "解析数据失败", "");
                    break;

            }
        }
    };



    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(getActivity(), "province.json");//获取assets目录下的json文件数据
        ArrayList<GeographyBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {

                    for (int d = 0; d < jsonBean.get(i).getCityList().get(c).getArea().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCityList().get(c).getArea().get(d);

                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }

    public ArrayList<GeographyBean> parseData(String result) {//Gson 解析

        ArrayList<GeographyBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                GeographyBean entity = gson.fromJson(data.optJSONObject(i).toString(), GeographyBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }


}
